
package com.gamatechno.solodestinationnew;

import it.gmariotti.cardslib.library.internal.Card;
import it.gmariotti.cardslib.library.internal.CardArrayAdapter;
import it.gmariotti.cardslib.library.view.CardGridView;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.facebook.HttpMethod;
import com.facebook.LoggingBehavior;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Settings;
import com.gamatechno.solodestinationnew.entity.E_Gallery;
import com.gamatechno.solodestinationnew.helper.JSONHelper;
import com.gamatechno.solodestinationnew.utils.Utils;
import com.gamatechno.solodestinationnew.utils.Webservice;

public class GalleryActivity extends BaseActivity implements OnScrollListener, OnClickListener {
    private static final String TAG = "GALLERY";
    private static final int SELECT_PICTURE = 1;
    private CardGridView cardGridView;
    private CardArrayAdapter adapter;
    private ProgressBar pBar;
    private ImageView btnImage;

    private List<E_Gallery> listGallery;
    private List<Card> listCard;

    private boolean isLoading = false;
    private boolean isMax = false;
    private int page = 0;
    private HashMap<String, String> params;
    private ProgressDialog pDialog;
    private String imgBase64;

    private Session.StatusCallback statusCallback = new SessionStatusCallback();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.activity_gallery);

        cardGridView = (CardGridView) findViewById(R.id.grid);
        pBar = (ProgressBar) findViewById(R.id.loader);
        btnImage = (ImageView) findViewById(R.id.btn_image);
        listCard = new ArrayList<Card>();
        listGallery = new ArrayList<E_Gallery>();

        Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
        Session session = Session.getActiveSession();

        if (session == null) {

            if (savedInstanceState != null)
                session = Session.restoreSession(this, null, statusCallback, savedInstanceState);
            if (session == null)
                session = new Session(this);

            Session.setActiveSession(session);
            if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
                session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
            }
        }
        updateState();

        adapter = new CardArrayAdapter(this, listCard);
        cardGridView.setAdapter(adapter);

        pDialog = new ProgressDialog(this);
        pDialog.setMessage("Uploading...");

        getListImage(Webservice.GET_LIST_PHOTO(page));
        cardGridView.setOnScrollListener(this);
        btnImage.setOnClickListener(this);
    }

    private void showLoading(boolean state) {
        cardGridView.setVisibility((state) ? View.GONE : View.VISIBLE);
        pBar.setVisibility((state) ? View.VISIBLE : View.GONE);
    }

    private void postPhoto(String URL) {
        StringRequest request = new StringRequest(Request.Method.POST,
                URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Utils.TRACE("GalleryActivity.postPhoto(...).new StringRequest() {...}",
                                "postPhoto : " + response);
                        pDialog.dismiss();
                        Toast.makeText(GalleryActivity.this, "Success", Toast.LENGTH_LONG).show();
                        // getListImage(Webservice.GET_LIST_PHOTO(page));
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Utils.TRACE("GalleryActivity.postPhoto(...).new StringRequest() {...}",
                                "postPhoto : " + error);
                        Utils.showVolleyError(GalleryActivity.this, error);
                        pDialog.dismiss();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                params = new HashMap<String, String>();

                params.put("method", "uploadPhoto");
                params.put("format", "json");
                params.put("user_id",
                        "" + Utils.getDataStringFromSP(GalleryActivity.this, Utils.PREF_FB_ID));
                params.put("name", Utils.getDataStringFromSP(GalleryActivity.this,
                        Utils.PREF_USERNAME));
                params.put("images", imgBase64);
                return params;
            }
        };
        BaseApplication.getInstance().addToRequestQueue(request, TAG);
        pDialog.show();

    }

    /**
     * get list image
     * 
     * @param URL
     */
    private void getListImage(String URL) {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
                URL,
                null,
                new Response.Listener<JSONObject>() {
                    public void onResponse(JSONObject response) {
                        Utils.TRACE("GalleryActivity.getListImage(...).new Listener() {...}",
                                "getListImage : " + response.toString());
                        isLoading = false;
                        if (page == 0)
                            showLoading(false);
                        else {
                            setSupportProgressBarIndeterminateVisibility(false);
                        }
                        try {
                            if (response.getInt("status") == 200) {
                                if (response.getJSONArray("result").length() > 0) {
                                    Utils.TRACE(
                                            "GalleryActivity.getListImag",
                                            "onResponse : length array "
                                                    + response.getJSONArray("result").length());
                                    List<E_Gallery> tmp = JSONHelper.getGallery(response
                                            .getJSONArray("result"));

                                    if (listGallery.size() > 0)
                                        listGallery.clear();

                                    for (E_Gallery gallery : tmp)
                                        listGallery.add(gallery);

                                    initCard(listGallery);
                                } else {
                                    isMax = true;
                                }
                            }
                        } catch (JSONException e) {
                            // TODO: handle exception
                        }

                    };
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        if (page == 0)
                            showLoading(false);
                        else {
                            setSupportProgressBarIndeterminateVisibility(false);
                        }

                        Utils.showVolleyError(GalleryActivity.this, error);
                        isLoading = false;
                    }
                });
        BaseApplication.getInstance().addToRequestQueue(request, TAG);
        if (page == 0)
            showLoading(true);
        else {
            setSupportProgressBarIndeterminateVisibility(true);
        }

        isLoading = true;
    }

    protected void initCard(List<E_Gallery> listGallery) {
        // TODO Auto-generated method stub
        for (int i = 0; i < listGallery.size(); i++) {
            listCard.add(new CardGallery(this, listGallery.get(i).getId(), Utils
                    .decodeBase64(listGallery.get(i).getPhoto()), listGallery.get(i).getPhoto(),
                    listGallery.get(i).getUploadBy()));
        }

        adapter.notifyDataSetChanged();

    }

    private class CardGallery extends Card {
        private Bitmap bmp;
        private int id;
        private String imgBase64;
        private String uploadedBy;

        public CardGallery(Context context, int id, Bitmap img, String imgBase64, String upload)
        {
            super(context, R.layout.item_card_grid_gallery);
            bmp = img;
            this.id = id;
            this.uploadedBy = upload;
            this.imgBase64 = imgBase64;
            init();
        }

        public void init() {
            setOnClickListener(new OnCardClickListener() {

                @Override
                public void onClick(Card card, View view) {
                    Bundle data = new Bundle();
                    data.putInt("id", id);
                    data.putString("img", imgBase64);
                    data.putString("upload", uploadedBy);
                    startActivity(new Intent(GalleryActivity.this, GalleryDetailActivity.class)
                            .putExtras(data));
                }
            });
        }

        @Override
        public void setupInnerViewElements(ViewGroup parent, View view) {
            super.setupInnerViewElements(parent, view);
            final ImageView img = (ImageView) view.findViewById(R.id.thumb_gallery);
            final ProgressBar pBar = (ProgressBar)
                    view.findViewById(R.id.loader);
            final TextView uploadName = (TextView) view.findViewById(R.id.uploaded_by);

            img.setImageBitmap(bmp);
            uploadName.setText(uploadedBy);
            // // ImageLoader.getInstance().dis

        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        // getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
            int totalItemCount) {
        // TODO Auto-generated method stub

        if (firstVisibleItem + visibleItemCount == totalItemCount && totalItemCount != 0
                && !isLoading && !isMax) {
            loadMoreData();
        }
    }

    /**
     * load more data
     */
    private void loadMoreData() {
        page++;
        getListImage(Webservice.GET_LIST_PHOTO(page));
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        // TODO Auto-generated method stub
    }

    private String getPath(Uri uri) {
        String[] projection = {
                MediaStore.Images.Media.DATA
        };

        Cursor cursor = managedQuery(uri, projection, null, null, null);
        if (cursor != null) {
            int col_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(col_index);
        } else {
            return null;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);

        if (requestCode == SELECT_PICTURE) {
            Utils.TRACE("GalleryActivity", "onActivityResult : " + resultCode);
            if (resultCode == RESULT_OK) {
                Utils.TRACE("GalleryActivity", "onActivityResult : " + data.toString());
                if (data != null) {

                    Uri selectedImage = null;
                    String filePath = null;
                    Bitmap bmp;

                    if (Build.VERSION.SDK_INT < 19) {
                        selectedImage = data.getData();
                    } else {
                        Utils.TRACE("AddPictureActivity",
                                "onActivityResult : ambil dari KITKAT "
                                        + data.getData());
                        InputStream input;
                        try {
                            input = this.getContentResolver().openInputStream(data.getData());
                            bmp = BitmapFactory.decodeStream(input);

                            ByteArrayOutputStream stream = new ByteArrayOutputStream();
                            bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
                            byte[] bytes = stream.toByteArray();

                            // startActivity(new Intent(this,
                            // UploadGalleryActivity.class).putExtra(
                            // "img", bytes));

                            // imgBase64 = Utils.encodeImageToBASE64(bmp);
                            // Utils.TRACE("GalleryActivity",
                            // "onActivityResult hasil image : "
                            // + imgBase64);
                        } catch (FileNotFoundException e) {
                            Utils.TRACE("AddPictureActivity",
                                    "onActivityResult : " + e.getMessage());
                        }
                    }

                    if (selectedImage != null) {
                        String fileManagerString = selectedImage.getPath();
                        Utils.TRACE("RegisterInaActivity", "onActivityResult: "
                                + getPath(selectedImage));
                        String selectedImagePath = getPath(selectedImage);

                        if (selectedImagePath != null)
                            filePath = selectedImagePath;
                        else if (fileManagerString != null)
                            filePath = fileManagerString;

                        if (filePath != null) {
                            imgBase64 = Utils.encodeImageToBASE64(Utils.decodeFile(filePath));
                            Utils.TRACE("GalleryActivity", "onActivityResult hasil jadi : "
                                    + imgBase64);
                            postPhoto(Webservice.POST_PHOTO_GALLERY);
                        }
                    }

                    // switch activity
                    // if (!TextUtils.isEmpty(imgBase64)) {
                    // startActivity(new Intent(this,
                    // UploadGalleryActivity.class).putExtra("img",
                    // imgBase64));
                    // }
                }

            }
        }
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (v == btnImage) {
            if (Utils.getDataBooleanFromSP(this, Utils.PREF_ISLOGIN)) {
                Intent pickIntent = new Intent();
                pickIntent.setType("image/*");
                pickIntent.setAction(Intent.ACTION_GET_CONTENT);
                Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                String pickTitle = "Select or take a new Picture"; // Or get
                                                                   // from
                                                                   // strings.xml
                Intent chooserIntent = Intent.createChooser(pickIntent, pickTitle);
                chooserIntent.putExtra
                        (
                                Intent.EXTRA_INITIAL_INTENTS,
                                new Intent[] {
                                    takePhotoIntent
                                }
                        );
                startActivityForResult(chooserIntent, SELECT_PICTURE);
            } else {
                Toast.makeText(this, "Need Login", Toast.LENGTH_SHORT).show();
                loginFB();
            }
        }
    }

    private void loginFB() {
        Session session = Session.getActiveSession();
        if (!session.isOpened() && !session.isClosed()) {
            Utils.TRACE("GalleryActivity", "loginFB : ");
            session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
        } else {
            Utils.TRACE("MainActivity", "onClick : session open");
            Session.openActiveSession(this, true, statusCallback);
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Session session = Session.getActiveSession();
        Session.saveSession(session, outState);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Utils.TRACE("GalleryActivity", "onStart : ");
        Session.getActiveSession().addCallback(statusCallback);
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        BaseApplication.getInstance().cancelPendingRequest(TAG);
        Session.getActiveSession().removeCallback(statusCallback);
    }

    private class SessionStatusCallback implements Session.StatusCallback {
        @Override
        public void call(Session session, SessionState state, Exception exception) {
            updateState();
        }
    }

    private void updateState() {
        Session session = Session.getActiveSession();
        if (session.isOpened()) {
            Utils.TRACE("GalleryActivity", "updateState : user login from facebook");
            Utils.setDataBooleanToSP(this, Utils.PREF_ISLOGIN, true);
            getUserData(session);
            // Toast.makeText(this, "Login succesfull",
            // Toast.LENGTH_SHORT).show();
        } else {
            Utils.TRACE("GalleryActivity", "updateState : state not opened");
        }
    }

    private void getUserData(Session session) {
        new com.facebook.Request(session, "/me", null, HttpMethod.GET,
                new com.facebook.Request.Callback() {

                    @Override
                    public void onCompleted(com.facebook.Response response) {
                        JSONObject jsonObject = null;
                        try {

                            jsonObject = new JSONObject(
                                    response.getGraphObject()
                                            .getInnerJSONObject()
                                            .toString());
                            Utils.TRACE("MainActivity.getUserData(...).new Callback() {...}",
                                    "onCompleted : " + jsonObject.toString());
                            Utils.setDataStringToSP(GalleryActivity.this, Utils.PREF_FB_ID,
                                    jsonObject.getString("id"));
                            Utils.setDataStringToSP(GalleryActivity.this,
                                    Utils.PREF_USERNAME,
                                    jsonObject.getString("name"));
                        } catch (JSONException e) {
                            Utils.TRACE("MenuUtamaActivity.getUserData(...).new Callback() {...}",
                                    "onCompleted : " + e.getMessage());
                        }
                    }
                }).executeAsync();
    }
}
